/**
 * \file stat.c
 * \brief fonctions g�rant la gestion de stat.
 * \author Quoc Cuong Do
 * \version 0.1
 * \date 11 septembre 2007
 *
 * Impl�mentation des fonctions servant � g�rer les stats
 *
 */

#include "stats.h"

#include "../utils/display.h"
#include "../utils/utils.h"

#include "../control/ctrl_mem.h"
#include "../control/ctrl_vol.h"
#include "../control/ctrl_station.h"


#include <msp430x14x.h>

#include <includes.h>
#include <stdlib.h>
#include <string.h>

extern OS_EVENT *ButtonMbox;

// Fonction de monitoring pour les stats
void updateStats()
{
	unsigned int volume;
	unsigned int station;

	volume = getVolume();
	station = getStationCourante();
	saveMode(getMode());
	saveVolume(getVolume());
	saveFrequence(getFrequence());
	saveStation(getStationCourante());
	augmenterVolTimeStat(volume,1);
	augmenterStationTimeStat(station,1);
	saveMemory();
}

char statsTxtBuffer[33];
char *volStatsTxt[] = { "Volume 1-6", "Volume 7-8" };

void displayStats(int idx)
{
	if (idx < NB_STATIONS)
	{
		displayStationStat(idx);
	}
	else
	{
		displayVolumeStat(idx - NB_STATIONS);
	}
}
void displayVolumeStat(int idx)
{	

	char *chaine,*nb;
	INT8U err;

	if (idx > 1 || idx < 0) return;

	chaine = statsTxtBuffer;

	nb = malloc(6*sizeof(char));
	*chaine = '\0';

	chaine = strcat(chaine,volStatsTxt[idx]);
	chaine = strcat(chaine,"\n");
	itoa(getVolTimeStat(idx*7+1),nb,10);
	chaine = strcat(chaine,nb);
	chaine = strcat(chaine,"s");

	free(nb);

	afficher(chaine);
}

void displayStationStat(int station)
{	
	char *chaine,*nb,**listeStations;
	INT8U err;
	listeStations = getListeStations();

	chaine = statsTxtBuffer;

	nb = malloc(6*sizeof(char));
	*chaine = '\0';

	chaine = strcat(chaine,listeStations[station]);
	chaine = strcat(chaine,"\n");
	itoa(getStationTimeStat(station),nb,10);
	chaine = strcat(chaine,nb);
	chaine = strcat(chaine,"s");

	free(nb);

	afficher(chaine);
}

// Tache de contultation des stats
void consultStats()
{
	int idx=0, button, run=1;
	INT8U err;
	while (run)
	{
		displayStats(idx);
		button = OSMboxPend(ButtonMbox, 0, &err);
		switch (button)
		{
			case COM_B1_LONG:
				afficher("Confimez la RAZ\n(Appui B4)");
				button = OSMboxPend(ButtonMbox, 0, &err);
				if (button == COM_B4) resetMemory();
				break;
			case COM_B1:
				run = 0;
				break;
			case COM_B3:
				if (idx < NB_STATIONS + 2) idx++;
				else idx = 0;
				break;
			case COM_B4:
				if (idx > 0) idx--;
				else idx = NB_STATIONS + 1;
				break;
		}
	}
}
